package com.kevin.netty.server.protocol.protobuf.handler;

import com.google.protobuf.util.JsonFormat;

import com.kevin.netty.protocol.protobuf.BasicMessage;
import com.kevin.netty.server.basic.AbstractInboundHandler;
import com.kevin.netty.starter.annotation.NettyHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Component
@ChannelHandler.Sharable
@NettyHandler(name = "protobuf", order = 1)
public class ProtobufInboundHandler extends AbstractInboundHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) {
        ByteBuf bf = (ByteBuf) o;
        byte[] data = new byte[bf.readableBytes()];
        bf.readBytes(data);

        try {
            BasicMessage.Basic basicMessage = BasicMessage.Basic.parseFrom(data);
            log.info("<<<<<< protobufInboundHandler 接收数据：{}", JsonFormat.printer().print(basicMessage));
        } catch (Exception e) {
            log.warn("hex : {}\nbyteArray : {}\nerror : {}", Arrays.toString(data), ByteBufUtil.hexDump(data), e.getMessage());
        }
    }

}
